package com.github.ecbp.common.security.utils;

import cn.hutool.core.date.DateUtil;
import com.github.ecbp.common.constant.CacheKeyConstant;
import com.github.ecbp.common.redis.RedisUtil;
import com.github.ecbp.common.security.config.JwtTokenConfig;
import com.github.ecbp.common.utils.IpAddressUtils;
import com.github.ecbp.common.utils.PlaceHolderUtils;
import com.google.common.collect.ImmutableMap;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * JwtToken生成的工具类
 * JWT token的格式：header.payload.signature
 * header的格式（算法、token的类型）：
 * {"alg": "HS512","typ": "JWT"}
 * payload的格式（用户名、创建时间、生成时间）：
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法：
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 * Created by macro on 2018/4/26.
 */
@Component
@PropertySource("classpath:jwt.properties")
public class JwtTokenUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    // 匿名用户
    public static final String ANONYMOUS_USER = "anonymousUser";
    // 未配置权限的接口权限
    public static final String NO_CONFIG_URL = "without:configuration:url";
    @Autowired
    private JwtTokenConfig tokenConfig;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, tokenConfig.getSecret())
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(tokenConfig.getSecret())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.error("token格式错误:{}", token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + tokenConfig.getJwtExpiration() * 1000);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getLoginPhoneFromToken(String token) {
        String userPhone;
        try {
            Claims claims = getClaimsFromToken(token);
            userPhone = claims.getSubject();
        } catch (Exception e) {
            userPhone = null;
        }
        return userPhone;
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String loginPhone = getLoginPhoneFromToken(token);
        return loginPhone.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 当原来的token没过期时是可以刷新的
     *
     * @param token token
     */
    public String refreshHeadToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        //token校验不通过
        Claims claims = getClaimsFromToken(token);
        if (claims == null) {
            return null;
        }
        //如果token已经过期，不支持刷新
        if (isTokenExpired(token)) {
            return null;
        }
        //如果token在30分钟之内刚刷新过，返回原token
        if (tokenRefreshJustBefore(token, 30 * 60)) {
            return token;
        } else {
            claims.put(CLAIM_KEY_CREATED, new Date());
            return generateToken(claims);
        }
    }

    /**
     * 判断token在指定时间内是否刚刚刷新过
     *
     * @param token 原token
     * @param time  指定时间（秒）
     */
    private boolean tokenRefreshJustBefore(String token, int time) {
        Claims claims = getClaimsFromToken(token);
        Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
        Date refreshDate = new Date();
        //刷新时间在创建时间的指定时间内
        if (refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, time))) {
            return true;
        }
        return false;
    }

    public Set<String> hasUserInfo(String loginPhone) {
        ImmutableMap<String, String> immutableMap = ImmutableMap.of(
                CacheKeyConstant.KEY, CacheKeyConstant.ADMIN_PREFIX,
                CacheKeyConstant.PHONE, loginPhone
        );
        return redisUtil.keysBySelect(PlaceHolderUtils.resolverString(CacheKeyConstant.USERINFO_IN_REDIS, immutableMap), 0);
    }

    public String getUserInfo(String loginPhone) {
        ImmutableMap<String, String> immutableMap = ImmutableMap.of(
                CacheKeyConstant.KEY, CacheKeyConstant.ADMIN_PREFIX,
                CacheKeyConstant.PHONE, loginPhone);
        return redisUtil.get(PlaceHolderUtils.resolverString(CacheKeyConstant.USERINFO_IN_REDIS, immutableMap), 0);
    }

    public void setUserInfo(String loginPhone, String value) {
        ImmutableMap<String, String> immutableMap = ImmutableMap.of(
                CacheKeyConstant.KEY, CacheKeyConstant.ADMIN_PREFIX,
                CacheKeyConstant.PHONE, loginPhone);
        setUserInfoByKey(PlaceHolderUtils.resolverString(CacheKeyConstant.USERINFO_IN_REDIS, immutableMap), value);
    }

    public void setUserInfoByKey(String key, String value) {
        redisUtil.set(key, value, 0);
    }

    public String getTokenFromRedis(String loginPhone) {
        return getTokenFromRedis(loginPhone, IpAddressUtils.getIpAddress(CommonAdminUtils.getRequest()));
    }

    public String getTokenFromRedis(String loginPhone, String ip) {
        ImmutableMap<String, String> immutableMap = ImmutableMap.of(
                CacheKeyConstant.KEY, CacheKeyConstant.TOKEN_PREFIX,
                CacheKeyConstant.PHONE, loginPhone,
                CacheKeyConstant.IP, ip
        );
        return redisUtil.get(PlaceHolderUtils.resolverString(CacheKeyConstant.TOKEN_IN_REDIS_WITH_IP, immutableMap), 0);
    }

    public void setTokenToRedis(String loginPhone, String authToken) {
        setTokenToRedis(loginPhone, authToken, IpAddressUtils.getIpAddress(CommonAdminUtils.getRequest()));
    }

    public void setTokenToRedis(String loginPhone, String authToken, String ip) {
        ImmutableMap<String, String> immutableMap = ImmutableMap.of(
                CacheKeyConstant.KEY, CacheKeyConstant.TOKEN_PREFIX,
                CacheKeyConstant.PHONE, loginPhone,
                CacheKeyConstant.IP, ip);
        redisUtil.set(PlaceHolderUtils.resolverString(CacheKeyConstant.TOKEN_IN_REDIS_WITH_IP, immutableMap), authToken,
                tokenConfig.getExpiration(), 0);

        // 当设置了token最大个数, 则会在同时登录的token个数超出时把时间最早的删除
        if (tokenConfig.getTokenSize() > 0) {
            Set<String> keys = redisUtil.keys(PlaceHolderUtils.resolverString(CacheKeyConstant.USERINFO_IN_REDIS, immutableMap) + "*");
            if (!CollectionUtils.isEmpty(keys) && keys.size() > tokenConfig.getTokenSize()) {
                List<Long> timeOut = new ArrayList<>();
                Map<Long, String> timeoutKey = new HashMap<>();
                for (String key : keys) {
                    Long ttl = redisUtil.ttl(key, 0);
                    timeoutKey.put(ttl, key);
                    timeOut.add(ttl);
                }
                timeOut.sort((o1, o2) -> o1 > o2 ? 1 : -1);
                redisUtil.del(timeoutKey.get(timeOut.get(0)));
            }
        }
    }

    public void removeTokenFromRedis(String loginPhone) {
        ImmutableMap<String, String> immutableMap = ImmutableMap.of(
                CacheKeyConstant.KEY, CacheKeyConstant.TOKEN_PREFIX,
                CacheKeyConstant.PHONE, loginPhone
        );
        final Set<String> keys = redisUtil.keysBySelect(PlaceHolderUtils.resolverString(CacheKeyConstant.TOKEN_IN_REDIS, immutableMap), 0);
        if (!CollectionUtils.isEmpty(keys)) {
            redisUtil.del(0, keys.toArray(new String[0]));
        }
    }

    public String getSalt() {
        return tokenConfig.getSalt();
    }

    public String getTokenHeader() {
        return tokenConfig.getTokenHeader();
    }
}
